﻿using System.Collections;
using System.IO;
using System;
using System.Collections.Generic;
using UnityEngine;
using System.Text;

public class FileUtil
{
    public static byte[] ReadBytes(string fileName)
    {
        string filePath = Path.Combine(configFolder, fileName);
        if (File.Exists(filePath))
        {
            return File.ReadAllBytes(filePath);
        }
        return null;
    }

    public static IEnumerator GetFileByEnumerater(string fileName,Action<byte[]> back)
    {
        WWW w = new WWW(configFolder+ fileName);
        yield return w;
        if (w.error == null)
        {
            back(w.bytes);
        }
        else
        {
            back(null);
        }
    }
    
    public static string configFolder
    {
        get
        {
            return Application.persistentDataPath;
        }
    }

    public static void SaveFile(string path,string fileName, string content)
    {
        Debug.Log("filePath:"+ path);
        Debug.Log("content:" + content);
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        string filPath = Path.Combine(path, fileName);
        byte[] bs = UTF8Encoding.UTF8.GetBytes(content);
        SaveFile(filPath, bs);
    }

    public static void SaveFile(string filePath, byte[] bs)
    {
        FileStream fs = File.Open(filePath, FileMode.OpenOrCreate);
        fs.Write(bs, 0, bs.Length);
        fs.Flush();
        fs.Close();
    }

    public static string GetMD5Hash(byte[] bytedata)
    {
        try
        {
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(bytedata);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            throw new Exception("GetMD5Hash() fail,error:" + ex.Message);
        }
    }
}
